import time

import socketio

from src.dicom_viewer_be_mock_xiaosai.utils.logger import logger
from src.dicom_viewer_be_mock_xiaosai.share import img_loader_dict

client_id = None
# 创建 Socket.IO 服务器
sio = socketio.AsyncServer(
                            cors_allowed_origins="*",
                            transports=['websocket'],
                            namespace='/ct',
                            ping_timeout=60,
                            ping_interval=25
                            )


# Socket.IO 事件处理
@sio.event(namespace='/ct')
async def connect(sid, environ):
    logger.info(f"Socket.IO client connected: {sid}")


@sio.event(namespace='/ct')
async def disconnect(sid):
    logger.info(f"Socket.IO client disconnected: {sid}")
    client_id = sid
    logger.info(f'断开连接，清除：client_id,{client_id}, ')


total_time = 0
count = 0

@sio.event(namespace='/ct')
async def message(sid, data):
    from src.dicom_viewer_be_mock_xiaosai.loader.ImgLoader import ImgLoader
    view_id = data['viewId']
    img_loader: ImgLoader = img_loader_dict.get(view_id, None)
    if img_loader is not None:
        # start_time = time.time()
        # 公司电脑 quick stack视图大约 0.015 ~ 0.02秒。
        await img_loader.handle_op(data)
        # end_time = time.time()
        # logger.info(f'发送图片耗时：{end_time - start_time}')

async def send_message_to_a_client(data):
    await sio.emit('image',
                   data,
                   room=client_id,  # 指定目标客户端的 sid
                   namespace='/ct')


async def send_message(msg):
    try:
        await send_message_to_a_client(msg)
    except Exception as e:
        logger.info(e)